package com.puzzlebazar.client.main.view;

import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;

public class RatingDisplay extends Composite {

	private int max = 5;
	private float rating = 0; // in percent
	private boolean allowHalf = true;

	private final String empty; 
//	private final String emptySel; 
	private final String full; 
//	private final String fullSel; 
	private final String half; 
//	private final String halfSel; 
	
	private final HorizontalPanel panel = new HorizontalPanel();
	
	/**
	 * Creates a widget to graphically display ratings. You should
	 * call updateDisplay() at some point after this function.
	 * The images used are:
	 *   prefixempty.png
	 *   prefixempty_sel.png
	 *   prefixfull.png
	 *   prefixfull_sel.png
	 *   prefixhalf .png     (only if half-ratings are enabled)
	 *   prefixhalf_sel.png  (only if half-ratings are enabled)
	 * 
	 * @param urlPrefix The url to use as prefix for images 
	 */
	public RatingDisplay( String urlPrefix ) {
		super();
	
		empty = urlPrefix + "empty.png";
//		emptySel = urlPrefix + "empty_sel.png";
		full = urlPrefix + "full.png";
//		fullSel = urlPrefix + "full_sel.png";
		half = urlPrefix + "half.png";
//		halfSel = urlPrefix + "half_sel.png";
		
		panel.setStylePrimaryName("ratingDisplay");
		
		initWidget( panel );
		
	}
	
	
	/**
	 * Updates the visual representation of the rating 
	 */
	public void updateDisplay() {
		panel.clear();
		
		int intRating;
		boolean needHalf = false;
		if( allowHalf ) {
			intRating = (int)(rating * (max * 2 - 1) + 0.5);
			if( intRating % 2 == 1 ) needHalf = true;
			intRating /= 2;
		}
		else
			intRating = (int)(rating * max + 0.5);
		
		int i;
		for( i=0; i<intRating; ++i ) {
			panel.add( new Image(full) );
		}
		if( needHalf ) {
			panel.add( new Image(half) );
			i++;
		}
		for( ; i<max; ++i ) {
			panel.add( new Image(empty) );
		}
	}


	/**
	 * Sets the maximum number of widgets to display
	 * You should call updateDisplay() at some point after this call.
	 * 
	 * @param max The maximum number of widgets to display
	 */
	public void setMax(int max) {
		this.max = max;
	}


	/**
	 * @return The maximum number of widgets to display
	 */
	public int getMax() {
		return max;
	}
	
	/**
	 * Sets the new rating to display
	 * You should call updateDisplay() at some point after this call.
	 * 
	 * @param rating The rating to display (in percentage)
	 */
	public void setRating(float rating) {
		this.rating = rating;
	}


	/**
	 * Indicates if the display allow half-full images for half-point ratings.
	 * You should call updateDisplay() at some point after this call.
	 * 
	 * @param allowHalf True to allow half-full images
	 */
	public void setAllowHalf(boolean allowHalf) {
		this.allowHalf = allowHalf;
	}
	
	
}
